package com.zxd.interview.conrruentbook;

import java.util.concurrent.Phaser;

/**
 * Phaser 工具类测试
 * 案例：模拟聚餐过程
 */
public class PhaserDinnerTest {

    public static void main(String[] args){
        PhaserDinner phaserDinner = new PhaserDinner();
        new Thread(new PhaserTask("张三", phaserDinner)).start();
        phaserDinner.register();
        new Thread(new PhaserTask("李四", phaserDinner)).start();
        phaserDinner.register();
        new Thread(new PhaserTask("王五", phaserDinner)).start();
        phaserDinner.register();
    }

    /**
     * 模拟聚餐的任务
     */
    private static  class PhaserDinner  extends Phaser{
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase){
                case 0:
                    return allArrive();
                case 1:
                    return allOrdered();
                case 2:
                    return allDrink();
                default:
                    return true;
            }
        }

        private boolean allDrink(){
            System.out.println("饮料点完了");
            return false;
        }

        /**
         * 模拟所有菜品已经点完
         * 菜品点完了
         */
        private boolean allOrdered(){
            System.out.println("菜品点完了");
            return false;
        }

        /**
         * 模拟所有人已经到齐
         * 所有人都到齐了，开始点餐
         */
        private boolean allArrive(){
            System.out.println("所有人都到齐了，开始点餐");
            return false;
        }
    }

    /**
     * 晚餐
     */
    private static class PhaserTask implements Runnable {
        private String name;
        private Phaser phaser;

        public PhaserTask(String name, Phaser phaser) {
            this.name = name;
            this.phaser = phaser;
        }

        @Override
        public void run() {
            //到达聚餐地点
            System.out.println(name + "--到达聚餐地点");
            phaser.arriveAndAwaitAdvance();

            //点菜品
            System.out.println(name + "--点了一份香辣牛肉");
            phaser.arriveAndAwaitAdvance();

            //点饮料
            System.out.println(name + "--点了一份常温豆奶");
            phaser.arriveAndAwaitAdvance();
        }
    }
}
